package com.junzhiit.nengji.shop.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.junzhiit.nengji.bo.GoodsInfoBO;
import com.junzhiit.nengji.dao.TypeDAO;
import com.junzhiit.nengji.model.Type;
import com.junzhiit.nengji.shop.service.TypeService;
import com.junzhiit.nengji.shop.web.util.Constants;
import com.junzhiit.nengji.shop.web.vo.ResultVO;
import com.junzhiit.nengji.shop.web.vo.TypeVO;

@Service
public class TypeServiceImpl extends BaseServiceImpl implements TypeService {
	
	@Autowired
	private TypeDAO typeDAO;

	@Override
	public ResultVO findAllGrading(String shopId) {
		ResultVO result = new ResultVO();
		List<Type> sourceList = source(shopId);
		List<TypeVO> aimsList = new ArrayList<TypeVO>();
		if (!sourceList.isEmpty()) {
			tree(aimsList, sourceList, Constants.ROOT_VALUE);
		}
		result.setData(aimsList);
		return result;
	}

	@Override
	public ResultVO getGoodsByType(String id) {
		ResultVO result=new ResultVO();
		List<GoodsInfoBO> list = typeDAO.getGoodsByType(id);
		result.setData(list);
		return result;
	}
	
	@Override
	public ResultVO getEatGoodsByType(String id,Integer type) {
		ResultVO result=new ResultVO();
		List<GoodsInfoBO> list = typeDAO.getEatGoodsByType(id,type);
		result.setData(list);
		return result;
	}
	
	private List<Type> source(String shopId){
		List<Type> sourceList = typeDAO.findAll(shopId);
		return sourceList;
	}
	
	private void tree(List<TypeVO> aimsList, List<Type> sourceList, String parentId) {
		for(int i = 0;i<sourceList.size();i++){
			Type type = sourceList.get(i);
			if (parentId.equals(type.getId())) {
				TypeVO typeVO = new TypeVO();
				BeanUtils.copyProperties(type, typeVO);
				aimsList.add(typeVO);
				sourceList.remove(type);
				typeVO.setChildren(new ArrayList<TypeVO>());
				tree(typeVO.getChildren(), sourceList, typeVO.getParentId());
				break;
			} else if (parentId.equals(type.getParentId())) {
				TypeVO typeVO = new TypeVO();
				BeanUtils.copyProperties(type, typeVO);
				aimsList.add(typeVO);
				sourceList.remove(type);
				i = -1;
				typeVO.setChildren(new ArrayList<TypeVO>());
				tree(typeVO.getChildren(), sourceList, typeVO.getId());
			}
		}
	}
}
